package com.lenovo.lcdm.team.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lenovo.lcdm.team.entity.TeamUser;
import com.lenovo.lcdm.team.entity.TeamUserGroup;
import com.lenovo.lcdm.team.mapper.TeamUserGroupMapper;
import com.lenovo.lcdm.team.service.ITeamUserGroupService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * User-Group Service
 * @author xujing30
 * @since 2023-12-22
 */
@Service
public class TeamUserGroupServiceImpl extends ServiceImpl<TeamUserGroupMapper, TeamUserGroup> implements ITeamUserGroupService {

    @Override
    public void saveOrUpdateUserGroups(TeamUser user, Set<Long> groups) {
        //先删除之前的关系
        LambdaQueryWrapper<TeamUserGroup> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUserGroup::getUserId, user.getId());
        this.remove(qw);

        List<TeamUserGroup> list = new ArrayList<>();
        for(Long group: groups){
            TeamUserGroup userGroup = new TeamUserGroup();
            userGroup.setUserId(user.getId());
            userGroup.setGroupId(group);
            userGroup.setCreator(user.getCreator());
            userGroup.setModifier(user.getCreator());
            userGroup.setCreateTime(LocalDateTime.now());
            userGroup.setModifyTime(LocalDateTime.now());
            list.add(userGroup);
        }
        this.saveBatch(list);
    }

    public List<TeamUserGroup> getGroupByUserId(Long userId){
        LambdaQueryWrapper<TeamUserGroup> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUserGroup::getUserId, userId);
        return this.list(qw);
    }

    @Override
    public List<TeamUserGroup> getUserByGroupId(Long groupId) {
        LambdaQueryWrapper<TeamUserGroup> qw = new LambdaQueryWrapper<>();
        qw.eq(TeamUserGroup::getGroupId, groupId);
        return this.list(qw);
    }
}
